package com.fengye.security.security.filter;

import com.fengye.security.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {


    private final JwtUtil jwtUtil;

    public JwtAuthenticationFilter(JwtUtil jwtUtil, AuthenticationManager authenticationManager) {
        super("/api/**", authenticationManager);
        this.jwtUtil = jwtUtil;
    }



    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String authorization = request.getHeader("Authorization");
        log.debug("authorization={}", authorization);
        String token = null;
        if (StringUtils.hasText(authorization)) {
            token = authorization.replaceFirst("Bearer ", "");
            log.debug("token={}", token);
        }

        if (StringUtils.hasText(token)) {
            String username = jwtUtil.getUsername(token);
            JwtAuthenticationToken authRequest = new JwtAuthenticationToken(username, null);
            authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return null;
    }
}
